﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace sqlsearcher
{
    public class HttpClient
    {
        public enum HttpMethod : int
        {
            get,
            post
        }

        public enum HttpContentType : int
        {
            [Description("application/json")]
            Json,
            [Description("application/x-www-form-urlencoded")]
            form
        }
        /// <summary>
        /// 设置请求的url
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string BuilderGetURL(HttpEntity entity)
        {
            var res = string.Empty;
            if (entity == null)
                return res;
            res = entity.HttpUrl;
            if (entity.HttpMethod.ToLower() == HttpMethod.get.ToString())
            {
                if (entity.Data!=null&&entity.Data.ToString()!="")
                {
                    res += "?";
                    res += entity.Data.ToString();
                    res = res.Replace("??", "?");
                }
            }
            return res;
        }



        /// <summary>
        /// 获取请求的数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string GetData(HttpEntity entity)
        {
            var res = string.Empty;
            if (entity == null)
                return res;

            if (entity.HttpMethod.ToLower() == HttpMethod.post.ToString())
            {
                if (entity.HttpContentType.IndexOf(EnumHelper.GetDescription<HttpContentType>((int)HttpContentType.form)) != -1)
                {
                    if (entity.Data != null)
                    {
                        res += "?";
                        res += entity.Data.ToString();
                        res = res.Replace("??", "?");
                    }
                }
                else if (entity.HttpContentType.IndexOf(EnumHelper.GetDescription<HttpContentType>((int)HttpContentType.Json)) != -1)
                {
                    res = entity.Data.ToString();
                }
            }
            return res;
        }

        /// <summary>
        /// Json格式化
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Task<Tuple<bool, string>> ConvertJsonString(string str)
        {
            try
            {
                return Task.Run(() =>
                {
                    try
                    {
                        //格式化json字符串
                        JsonSerializer serializer = new JsonSerializer();
                        TextReader tr = new StringReader(str);
                        JsonTextReader jtr = new JsonTextReader(tr);
                        object obj = serializer.Deserialize(jtr);
                        if (obj != null)
                        {
                            StringWriter textWriter = new StringWriter();
                            JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                            {
                                Formatting = Formatting.Indented,
                                Indentation = 4,
                                IndentChar = ' '
                            };
                            serializer.Serialize(jsonWriter, obj);
                            return Tuple.Create(true, textWriter.ToString());
                        }
                        else
                        {
                            return Tuple.Create(false, str);
                        }
                    }
                    catch (Exception ex)
                    {
                        return Tuple.Create(false, str);
                    }
                });
            }
            catch (Exception)
            {
                return new Task<Tuple<bool, string>>((m)=>Tuple.Create(false,""),TaskCreationOptions.None);
            }
        }

        public string Send(HttpEntity entity)
        {
            string responseContent = string.Empty;
            try
            {

                var url = BuilderGetURL(entity);

                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.Method = entity.HttpMethod.ToLower();
                httpWebRequest.Timeout = 20000;

                if (entity.HttpMethod.ToLower() == HttpMethod.post.ToString())
                {
                    byte[] bs = Encoding.UTF8.GetBytes(GetData(entity));
                    httpWebRequest.ContentType = entity.HttpContentType;
                    httpWebRequest.ContentLength = bs.Length;
                    httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
                }

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                responseContent = streamReader.ReadToEnd();


                streamReader.Close();
                httpWebResponse.Close();
                httpWebRequest.Abort();
            }
            catch (Exception ex)
            {
                responseContent = ex.Message;
            }

            return responseContent;

        }
    }
}